<template>
  <transition appear name="fadeIn">
    <div
      class="message"
      :style="{
        backgroundColor: colorMap[type].backgroundColor,
        color: colorMap[type].color,
        top: offset + 'px',
      }"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
    >
      <slot>
        <p>{{ message }}</p>
      </slot>
    </div>
  </transition>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, defineProps } from "vue";
type colorType = {
  backgroundColor: string;
  color: string;
};
type colorMapType = {
  success: colorType;
  error: colorType;
};
type typeType = "success" | "error";
const colorMap = ref<colorMapType>({
  success: { backgroundColor: "#f2f9ec", color: "#7ec050" },
  error: { backgroundColor: "#fcf0f0", color: "#e7827e" },
});
const props = defineProps({
  message: {
    type: String,
    default: "",
  },
  type: {
    type: String as () => typeType,
    default: "success",
  },
  offset: {
    type: Number,
    default: 20,
  },
  onClose: {
    type: Function,
    default: () => {},
  },
  id: {
    type: String,
    default: "",
  },
});

const visible = ref<boolean>(true);
const duration = ref<number>(3000);
const closed = ref<boolean>(false);
// const verticalOffset = ref<number>(20);
const timer = ref<number | null>(null);
// const dangerouslyUseHTMLString: false,
const center = ref<boolean>(false);

onMounted(() => {
  startTimer();
  document.addEventListener("keydown", keydown);
});
watch(
  () => closed.value,
  (val) => {
    if (val) {
      visible.value = false;
    }
  },
  {
    immediate: true, //关键
    deep: true,
  }
);
// const handleAfterLeave = () => {
//   $destroy(true);
//   $el.parentNode.removeChild($el);
// };

const close = () => {
  visible.value = false;
};

const clearTimer = () => {
  if (timer.value !== null) clearTimeout(timer.value);
};
const startTimer = () => {
  if (duration.value > 0) {
    timer.value = setTimeout(() => {
      visible.value = false;
      props.onClose();
    }, duration.value);
  }
};
const keydown = (e: KeyboardEvent) => {
  if (e.keyCode === 27) {
    // esc关闭消息
    props.onClose();
  }
};

const beforeDestroy = () => {
  document.removeEventListener("keydown", keydown);
};
</script>

<style lang="scss" scoped>
.message {
  min-width: 200px;
  position: absolute;
  width: 22%;
  font-size: 13px;
  height: 40px;
  text-align: center;
  margin: auto;
  left: 0;
  right: 0;
  border-radius: 10px;
  z-index: 9999999;
  transition: all 0.3s;
  p {
    margin: 0;
    line-height: 40px;
  }
}
</style>
